package com.hsgene.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.order.exception.OrderErrorCode;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @description: 获取二维码
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.order.controller
 * @author: maodi
 * @createDate: 2018/9/29 16:45
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing")
public class QrcodeController {

    @Value("${qrcode.url}")
    private String qrcodeUrl;
    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(QrcodeController.class);

    /**
     * @param gtonId 检测报告单号
     * @return com.hsgene.common.util.result.ApiResult<java.lang.String>
     * @description 获取二维码
     * @author maodi
     * @createDate 2018/9/29 17:32
     */
    @GetMapping("orders/{order_id}/qrcode")
    public ApiResult<String> getQrcode(@PathVariable("order_id") String gtonId) {
        try {
            String qrcodeUrl = getQrcodeByHttpGet(gtonId);
            if (StringUtils.isBlank(qrcodeUrl)) {
                return ApiResult.fail(OrderErrorCode.GET_QRCODE_IS_ERROR);
            }
            return ApiResult.succ(qrcodeUrl);
        } catch (Exception e) {
            LOGGER.error("get qrcode is error", e);
            return ApiResult.fail(OrderErrorCode.GET_QRCODE_IS_ERROR);
        }
    }

    /**
     * @param gtonId 检测报告单号
     * @return java.lang.String
     * @description 请求琉璃堂接口获取二维码
     * @author maodi
     * @createDate 2018/9/29 17:32
     */
    public String getQrcodeByHttpGet(String gtonId) {
        String hUrl = qrcodeUrl + gtonId;
        if (StringUtils.isBlank(qrcodeUrl)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(hUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            //只有https才需要加安全验证，http直接跳过
            if (hUrl.startsWith("https")) {
                //此处写了个假的安全验证，以便请求https能够成功
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
                ((HttpsURLConnection) con).setSSLSocketFactory(sc.getSocketFactory());
                ((HttpsURLConnection) con).setHostnameVerifier(new TrustAnyHostnameVerifier());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                sb.append(inputLine);
            }
            reader.close();
        } catch (Exception e) {
            LOGGER.error("请求生成临时二维码出错", e);
        }
        JSONObject json = JSONObject.parseObject(sb.toString());
        return json.getString("url");
    }

    private static class TrustAnyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

}
